package com.qingyun.feedbackservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingyun.common.dto.Result;
import com.qingyun.common.util.UserHolder;
import com.qingyun.feedbackservice.client.ScheduleClient;
import com.qingyun.feedbackservice.dto.FeedbackDTO;
import com.qingyun.feedbackservice.dto.FeedbackPhotoDTO;
import com.qingyun.feedbackservice.dto.ScheduleInfoDTO;
import com.qingyun.feedbackservice.entity.Feedback;
import com.qingyun.feedbackservice.entity.FeedbackPhoto;
import com.qingyun.feedbackservice.mapper.FeedbackMapper;
import com.qingyun.feedbackservice.mapper.FeedbackPhotoMapper;
import com.qingyun.feedbackservice.service.IFeedbackService;
import com.qingyun.feedbackservice.vo.FeedbackVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课堂反馈 服务实现类
 * </p>
 */
@Slf4j
@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements IFeedbackService {
    
    @Autowired
    private UserHolder userHolder;
    
    @Autowired
    private FeedbackPhotoMapper feedbackPhotoMapper;
    
    @Autowired
    private ScheduleClient scheduleClient;


    @Override
    public Result listByStudent(Long studentId, String token) {
        if (studentId==null){
            return Result.fail("学生ID为空");
        }
        Long userId = userHolder.getUserId();
        // 查询反馈列表
        List<FeedbackVO> list = baseMapper.briefList(studentId, userId, null);
        if(list.isEmpty()){
            return Result.fail("暂无该学生课堂反馈信息");
        }
        // 通过Feign调用获取课表信息
        List<FeedbackVO> enrichedList = new ArrayList<>();
        for (FeedbackVO feedback : list) {
            if (feedback.getScheduleId() != null) {
                try {
                    Result scheduleResult = scheduleClient.getScheduleInfo(feedback.getScheduleId());
                    if (BooleanUtil.isTrue(scheduleResult.getSuccess()) && scheduleResult.getData() != null) {
                        ScheduleInfoDTO scheduleInfo = (ScheduleInfoDTO) scheduleResult.getData();
                        feedback.setTeachDate(scheduleInfo.getTeachDate());
                        feedback.setStartTime(scheduleInfo.getStartTime());
                        feedback.setEndTime(scheduleInfo.getEndTime());
                        feedback.setCourseName(scheduleInfo.getCourseName());
                    }
                    else{
                        return Result.fail("当前课堂反馈暂无课表信息，请联系管理员");
                    }
                } catch (Exception e) {
                    log.warn("获取课表信息失败，scheduleId: {}", feedback.getScheduleId(), e);
                }
            }
            enrichedList.add(feedback);
        }
        
        return Result.ok(enrichedList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result postFeedback(FeedbackDTO feedbackDTO) {
        if (feedbackDTO == null) {
            return Result.fail("课堂反馈信息为空");
        }

        // 创建反馈记录
        Feedback feedback = BeanUtil.copyProperties(feedbackDTO, Feedback.class);
        feedback.setScheduleId(feedbackDTO.getScheduleId());
        feedback.setStudentId(feedbackDTO.getStudentId());
        feedback.setCreateTime(LocalDateTime.now());
        feedback.setUpdateTime(LocalDateTime.now());
        feedback.setTeacherId(userHolder.getUserId());

        baseMapper.insert(feedback);
        Long feedbackId = feedback.getId();
        log.info("反馈提交成功，ID: {}", feedbackId);

        // 处理图片数据
        if (feedbackDTO.getPhotos() == null || feedbackDTO.getPhotos().isEmpty()) {
            throw new IllegalArgumentException("图片路径不能为空");
        }

        saveFeedbackPhotos(feedbackId, feedbackDTO.getPhotos());
        log.info("保存反馈图片成功，共{}张", feedbackDTO.getPhotos().size());

        return Result.ok();
    }
    
    /**
     * 保存反馈图片URL
     */
    private void saveFeedbackPhotos(Long feedbackId, List<FeedbackPhotoDTO> photos) {
        for (FeedbackPhotoDTO photoDTO : photos) {
            FeedbackPhoto feedbackPhoto = new FeedbackPhoto();
            feedbackPhoto.setFeedbackId(feedbackId);
            feedbackPhoto.setUrl(photoDTO.getUrl());
            feedbackPhoto.setSortNo(photoDTO.getSortNo());
            feedbackPhoto.setCreateTime(LocalDateTime.now());
            feedbackPhotoMapper.insert(feedbackPhoto);
        }
    }
    


    @Override
    public Result uploadFeedbackPhotos(MultipartFile[] files, String token) {
        if (files == null || files.length == 0) {
            return Result.fail("请选择要上传的图片文件");
        }

        List<Map<String, Object>> dataList = new ArrayList<>();
        List<String> failedFiles = new ArrayList<>();

        for(MultipartFile file : files){
            try {
                if (file == null || file.isEmpty()) {
                    failedFiles.add("文件为空");
                    continue;
                }

                Map<String, Object> data = new HashMap<>();
                // 这里应该调用文件上传服务或对象存储服务
                String fileName = "temp_" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
                String imageUrl = "/uploads/feedback/images/" + fileName;

                Files.copy(file.getInputStream(), Paths.get("/uploads/feedback/images/" + fileName));

                data.put("url", imageUrl);
                data.put("fileName", fileName);
                data.put("originalName", file.getOriginalFilename());
                data.put("size", file.getSize());
                dataList.add(data);

            } catch (Exception e) {
                log.error("图片上传异常: {}", file.getOriginalFilename(), e);
                failedFiles.add(file.getOriginalFilename());
            }
        }

        if (dataList.isEmpty()) {
            return Result.fail("所有图片上传失败");
        } else if (!failedFiles.isEmpty()) {
            log.warn("部分图片上传失败: {}", failedFiles);
        }

        return Result.ok(dataList);
    }
    
    @Override
    public List<String> getFeedbackPhotos(Long feedbackId) {
        try {
            List<FeedbackPhoto> photos = feedbackPhotoMapper.selectByFeedbackId(feedbackId);
            List<String> photoUrls = new ArrayList<>();
            
            for (FeedbackPhoto photo : photos) {
                photoUrls.add(photo.getUrl());
            }
            
            return photoUrls;
        } catch (Exception e) {
            log.error("获取反馈图片时发生异常，feedbackId: {}", feedbackId, e);
            return new ArrayList<>();
        }
    }
}